import { Node } from "cc";
import { Snake } from "./Snake";
import { SnakeBody } from "./SnakeBody";

/**
 * 蛇管理器
 */
export class SnakeMgr {

    snakeMap = new Map<number, Snake>();
    bodyMap = new Map<number, SnakeBody>();

    constructor(
        /** 游戏层级 */
        public readonly layer: Node
    ) { }

    addSnake(data: kp_snake_snake) {
        const node = new Node(data.name);
        const snake = node.addComponent(Snake).onInit(data);
        this.snakeMap.set(data.id, snake);
        this.layer.addChild(node);
    }

    updateSnake(data: kp_snake_snake) {
        this.snakeMap.get(data.id)?.updateData(data);
    }

    /**
     * 接收到实体蛇数据
     * @param type 1:add 2:update
     * @param data 
     */
    onEntitySnakeData(type: number, data: kp_entity_snake) {
        const snake = this.snakeMap.get(data.id);
        if (snake) {
            snake.updateSize(data.size);
            if (type === 1) {
                data.bodys.forEach(bodyData => {
                    const body = snake.addBody(bodyData);
                    this.bodyMap.set(bodyData.id, body);
                });
            } else if (type == 2) {
                data.bodys.forEach(bodyData => {
                    snake.updateBody(bodyData);
                });
            }
        }
    }

    /**
     * 接收到实体移除
     * @param id 
     */
    onEntityRemove(id: number) {
        const body = this.bodyMap.get(id);
        if (body) {
            body.snake.removeBody(id);
            this.bodyMap.delete(id);
        }
    }

}